package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.*;
import com.heima.article.service.ApArticleService;
import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.feigns.user.UserFeign;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.*;
import com.heima.model.behavior.dtos.ApArticleRelationDto;
import com.heima.model.common.constants.ArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import io.seata.common.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;


@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {






    @Autowired
    AuthorMapper authorMapper;
    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    ApArticleContentMapper apArticleContentMapper;

    @Autowired
    ApArticleMapper apArticleMapper;

    @Autowired
    UserFeign userFeign;
    @Autowired
    BehaviorFeign behaviorFeign;

    @Autowired
    ApCollectionMapper apCollectionMapper;
    /**
     * 加载文章详情的初始化配置信息，比如关注、喜欢、不喜欢等
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {


        //参数检查
        if (dto == null || dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.okResult(new HashMap<>());
        }

        //查询是否关注
        boolean iscollection=false,isfollow=false;
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null) {
            return ResponseResult.okResult(new HashMap<>());
        }
        ApAuthor apAuthor = authorMapper.selectById(dto.getAuthorId());
        if (apAuthor == null) {
            return ResponseResult.okResult(new HashMap<>());
        }

        ApUserFollow apUserFollow = userFeign.findByUserIdAndFollowId(apUser.getId(), apAuthor.getUserId());
        if (apUserFollow != null) {
            isfollow=true;
        }

        //查询是否不喜欢/点赞
        ApArticleRelationDto reDto = new ApArticleRelationDto();
        reDto.setArticleId(dto.getArticleId());
        reDto.setEntryId(apUser.getId());
        reDto.setType((short) 1);
        Map map = behaviorFeign.findApArticleRelation(reDto);
        //查询是否收藏
        if (map.get("entryId") != null) {
            ApCollection apCollection = apCollectionMapper.selectOne(Wrappers.<ApCollection>lambdaQuery()
                    .eq(ApCollection::getArticleId, dto.getArticleId())
                    .eq(ApCollection::getEntryId, map.get("entryId"))
                    .eq(ApCollection::getType, ApCollection.Type.ARTICLE.getCode())
            );
            if (apCollection!=null){
                iscollection=true;
            }
        }

        //封装结果并返回
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("iscollection",iscollection);
        resultMap.put("isfollow",isfollow);
        resultMap.putAll(map);
        return ResponseResult.okResult(resultMap);
    }

    /**
     * 加载文章详情
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArtilceInfo(ArticleInfoDto dto) {
        if(dto==null||dto.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Long id = dto.getArticleId();
        //查询文章配置信息
        ApArticleConfig apArticleConfig = apArticleConfigMapper.selectById(Wrappers.<ApArticleConfig>lambdaQuery()
                .eq(ApArticleConfig::getArticleId, id));
        if (apArticleConfig==null||apArticleConfig.getIsDown()||apArticleConfig.getIsDelete()){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"文章已经下架");
        }
        //查询文章内容信息
        ApArticleContent apArticleContent = apArticleContentMapper.selectById(Wrappers.<ApArticleContent>lambdaQuery()
                .eq(ApArticleContent::getArticleId, id)
        );
        if(apArticleContent==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"文章不存在");
        }
        Map<String,Object> map = new HashMap<>();
        map.put("config",apArticleConfig);
        map.put("content",apArticleContent);

        return ResponseResult.okResult(map);
    }

    @Value("${file.oss.web-site}")
    private String webSite;

    /**
     * 根据参数加载文章列表
     *
     * @param loadtype 1为加载更多  2为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {
        if(dto==null){
            dto = new ArticleHomeDto();
        }
        Integer size = dto.getSize();
        if(size==null||size<=0){
            size=10;
        }
        if (size==null||size>50){
        size=Math.min(size,50);
        }
        dto.setSize(size);
        if (StringUtils.isBlank(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        if (dto.getMaxBehotTime()==null){
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime()==null){
            dto.setMinBehotTime(new Date());
        }
        if(!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE)&&!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)){
            loadtype=ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        List<ApArticle> apArticleList = apArticleMapper.loadArticleList(dto, loadtype);
        ResponseResult responseResult = ResponseResult.okResult(apArticleList);
        responseResult.setHost(webSite);
        return responseResult;
    }

    /**
     * 保存或修改文章
     *
     * @param articleDto
     * @return
     */
    @Override
    public ResponseResult saveArtilce(ArticleDto articleDto) {
        //参数检查
        if(articleDto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //保存文章数据,设置作者id
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(articleDto,apArticle);
        //设置作者id,先查后设置
        String authorName = articleDto.getAuthorName();
        ApAuthor apAuthor = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getName,authorName ));

        if(apAuthor==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        apArticle.setAuthorId(apAuthor.getId().longValue());
        if(articleDto.getId()==null){
            //保存
            apArticle.setComment(0);
            apArticle.setViews(0);
            apArticle.setCollection(0);
            apArticle.setLikes(0);

            save(apArticle);

            //2 保存article_config 数据
            ApArticleConfig apArticleConfig = new ApArticleConfig();
            apArticleConfig.setIsForward(true);
            apArticleConfig.setIsComment(true);
            apArticleConfig.setIsDown(false);
            apArticleConfig.setIsDelete(false);

            apArticleConfig.setArticleId(apArticle.getId());

            apArticleConfigMapper.insert(apArticleConfig);

            //保存文章数据
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setContent(articleDto.getContent());

            apArticleContent.setArticleId(apArticle.getId());
            apArticleContentMapper.insert(apArticleContent);

        }else{
            //修改,先查再改

            ApArticle article = getById(articleDto.getId());
            if(article==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
            }

            //修改
            updateById(apArticle);
            //修改文章内容,先查再改
            ApArticleContent articleContent = apArticleContentMapper.selectOne( Wrappers.<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId,articleDto.getId() ));
            if (articleContent==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
            }
            articleContent.setContent(articleDto.getContent());
            apArticleContentMapper.updateById(articleContent);

        }
        //返回文章保存后的主键id
        return ResponseResult.okResult(apArticle.getId());
    }
}